/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.gson.Gson;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.emergency.bean.BaseQuery;
import com.koron.emergency.bean.DrillPlanAttrBean;
import com.koron.emergency.domain.DrillPlan;
import com.koron.emergency.service.api.DrillPlanService;
import com.koron.emergency.util.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(tags = "drillPlan",description = "演练计划相关接口")
@RestController
@RequestMapping("/drillPlan")
public class DrillPlanController {

    @Autowired
    private DrillPlanService service;

    private final static Logger log = LoggerFactory.getLogger(DrillPlanController.class);


    @ApiOperation("保存演练计划接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name", value = "演练计划名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "purpose", value = "演练目的", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "manager", value = "演练负责人code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "managerName", value = "演练负责人名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "place", value = "演练地点", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "drillMethod", value = "演练方式，0桌面演练1功能演练2全面演练", required = true, dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "drillTime", value = "计划演练时间，格式为yyyy-MM-dd HH:mm:ss", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sponsorDeptCode", value = "主办部门code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sponsorDeptName", value = "主办部门名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "cooperationDeptCode", value = "协办部门code,多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "cooperationDeptName", value = "协办部门名称，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "contingencyPlanId", value = "应急预案id", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "remrak", value = "备注",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "participant", value = "参与人员code，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "participantName", value = "参与人员姓名和部门姓名，staffname_deptname，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "approver", value = "审批人", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "drillType", value = "演练类型", required = true, dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "drillPeopleNum ", value = "参与人数",  dataType = "int",paramType = "query")
    })
    @RequestMapping(value = "/save.htm",method = RequestMethod.POST)
    @Log(title = "保存演练计划",businessModule = "应急演练", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore DrillPlan bean, @RequestParam final String approver,@RequestBody MultipartFile[] files){
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        if (StringUtils.isNotEmpty(bean.getCooperationDeptCode())){
            String[] codes=bean.getCooperationDeptCode().split("[,，]");
            bean.setCooperationDeptCode(new Gson().toJson(Arrays.asList(codes)));
        }
        if (StringUtils.isNotEmpty(bean.getCooperationDeptName())){
            String[] names=bean.getCooperationDeptName().split("[,，]");
            bean.setCooperationDeptName(new Gson().toJson(Arrays.asList(names)));
        }
        if (StringUtils.isNotEmpty(bean.getParticipant())){
            String[] codes=bean.getParticipant().split("[,，]");
            bean.setParticipant(new Gson().toJson(Arrays.asList(codes)));
        }
        if (StringUtils.isNotEmpty(bean.getParticipantName())){
            String[] names=bean.getParticipantName().split("[,，]");
            bean.setParticipantName(new Gson().toJson(Arrays.asList(names)));
        }
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        bean.setUpdateTime(new Date());
        return service.save(user,bean,approver,files);
    }

    @ApiOperation("删除演练计划接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "演练计划id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "approver", value = "审批人", required = true, dataType = "String",paramType = "query")
    })
    @RequestMapping(value = "/delete.htm",method = RequestMethod.POST)
    @Log(title = "删除演练计划", businessModule = "应急演练", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> deleteEmergency(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,@RequestParam final String id,@RequestParam final String approver){
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return service.delete(user,id,approver);
    }

    @ApiOperation("查询单个演练计划详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "演练计划id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/details.htm",method = RequestMethod.POST)
    public MessageBean<DrillPlan> details(@RequestParam final String id){

        return service.queryOne(id);
    }

    @ApiOperation("演练计划列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "计划名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sponsorDeptCode",value = "主办单位code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "startTime",value = "演练计划开始时间，格式为：yyyy-MM-dd",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "endTime",value = "演练计划结束时间，格式为：yyyy-MM-dd",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/list.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<DrillPlan>> list(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String sponsorDeptCode,
                                                 @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8") @DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(required = false) final Date startTime,
                                                 @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")  @DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(required = false) final Date endTime,
                                                 @RequestParam Integer page,  @RequestParam Integer pageSize){
        Integer start=null;
        if (page==null||page<=0){
            page=1;
            if (pageSize==null||pageSize<=0){
                pageSize=15;
            }
        }
        start=(page<=1)?0:(page-1)*pageSize;
        MessageBean<DataBean<DrillPlan>>msg= service.queryByCondition(corpCode, name,sponsorDeptCode, startTime, endTime, start, pageSize);
        if (null!=msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("导出演练计划")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "计划名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sponsorDeptCode",value = "主办单位code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "startTime",value = "演练计划开始时间，格式为：yyyy-MM-dd",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "endTime",value = "演练计划结束时间，格式为：yyyy-MM-dd",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/export.htm",method = RequestMethod.GET)
    public HttpEntity<?> export(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String sponsorDeptCode,
                                @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8") @DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(required = false) final Date startTime,
                                @JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")  @DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(required = false) final Date endTime){
        Map<String,Object> map=new HashMap<>();
        MessageBean<DataBean<DrillPlan>> msg=service.queryByCondition(corpCode, name,sponsorDeptCode, startTime, endTime,null,null);
        if (msg.getData()!=null){
            map.put("data",msg.getData().getList());
        }
        File targetFile = new File("static/excel/drillplan.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/drillplan.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Excel.createFile("应急演练列表",targetFile, "drillplan.btl",map);
    }

    @ApiOperation("演练评估-选择演练计划接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "计划名称",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/queryAll.htm",method = RequestMethod.POST)
    public MessageBean<List<DrillPlan>> queryAll(@RequestParam final String corpCode, @RequestParam(required = false) final String name){
        return service.queryAll(corpCode,name);
    }

    @ApiOperation("查询所有开通水司安全检查统计分析列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name="beginTime",value = "开始时间",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="endTime",value = "结束时间",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="page",value = "当前页",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name="pageCount",value = "每页条数",required = true,dataType = "int",paramType = "query")
    })
    @RequestMapping(value = "/safetyAccount.htm",method = RequestMethod.POST)
    public MessageBean<?> safetyAccount(@RequestParam(required = false) final String name,
                                        @RequestParam(required = false) final String code,
                                        @RequestParam(required = false) final Integer page,
                                        @RequestParam(required = false) final Integer pageCount,
                                        @RequestParam(required = false) final String beginTime,
                                        @RequestParam(required = false) final String endTime){
        BaseQuery baseQuery = new BaseQuery(name, code, beginTime, endTime);
        baseQuery.setPage(page);
        baseQuery.setPageCount(pageCount);
        return service.safetyAccount(baseQuery);
    }

    @ApiOperation("查询该演练计划附件")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "id",required = true,dataType = "String",paramType = "query")
    })
    @RequestMapping(value = "/fileList.htm",method = RequestMethod.POST)
    public MessageBean<List<DrillPlanAttrBean>> fileList(@RequestParam(required = true) String id){
        return ADOConnection.runTask(factory -> service.fileList(factory,id),MessageBean.class);
    }
}
